package com.education.cloud.util.interceptor;

import cn.hutool.core.util.StrUtil;
import com.education.cloud.util.constant.Constants;
import com.education.cloud.util.base.BaseException;
import com.education.cloud.util.base.Result;
import com.education.cloud.util.constant.Constants;
import com.education.cloud.util.tools.WebUtil;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description token校验拦截器
 * @Date 2020/3/22
 * @Created by 67068
 */
public class ServerProtectInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        // 从请求头中获取 Gateway Token
        String gatewayToken = request.getHeader(Constants.GATEWAY_TOKEN_HEADER);
        String zuulToken = new String(Base64Utils.encode(Constants.GATEWAY_TOKEN_VALUE.getBytes()));
        // 校验 Gateway Token的正确性
        if (StrUtil.equals(zuulToken, gatewayToken)) {
            return true;
        } else {
            WebUtil.makeResponse(response, MediaType.APPLICATION_JSON_VALUE,
                    HttpServletResponse.SC_FORBIDDEN, Result.error("请通过网关获取资源"));
            return true;
        }
    }
}
